<template>
  <a-auto-complete :options="mOptions" @search="handleSearch">
    <template v-for="item in slotKeys.filter(key=>props[key])" #[item]="slotProps">
      <component :is="renderSlot(props,item,slotProps || {})"/>
    </template>
  </a-auto-complete>
</template>
<script setup lang="ts">
import { DefaultOptionType } from 'ant-design-vue/lib/select';
import { PropType, VNode, ref, watch } from 'vue';
import { renderSlot } from '../index'
import request from '/@/utils/request'

const slotKeys = ['default','placeholder','option']
const props = defineProps({
  options: {
    type: [Array] as PropType<DefaultOptionType[]>
  },
  default: {
    type: [String, Object, Function] as PropType<String | VNode |(()=>VNode | String)>
  },
  placeholder: {
    type: [String, Object, Function] as PropType<String | VNode |(()=>VNode | String)>
  },
  option: {
    type: [String, Object, Function] as PropType<String | VNode |(()=>VNode | String)>
  },
  onSearch: {
    type: Function as PropType<(searchText: string)=>void>
  },
  api: { // 接口地址或接口函数--->新增属性
    type: [Function, String] as PropType<((param: any)=>Promise<any>) | String>
  },
})
const mOptions = ref(props.options || [])
watch(()=>props.options,()=>{
  mOptions.value = props.options as any
},{
  deep: true
})
const requestData = (params: any): Promise<any> => {
  let apiFun: ((param: any)=>Promise<any>) | undefined
  return new Promise((resolve, reject)=>{
    if(props.api && typeof props.api == 'function') {
      apiFun = props.api
    } else if(props.api && typeof props.api == 'string') {
      apiFun = (param: any) => request.post(props.api as any, param)
    }
    if(apiFun) {
      apiFun({
        ...params
      }).then((res: any)=>{
        mOptions.value = res.data || res
        resolve(res)
      }).catch(reject)
    } else {
      resolve({})
    }
  })
}
const handleSearch = (searchText: string) =>{
  if(props.onSearch && typeof props.onSearch == 'function') {
    props.onSearch(searchText)
  } else {
    requestData({
      keywords: searchText
    })
  }
}
const regisiter = {
  setOptions(options: any){
    mOptions.value = options
  },
  getOptions(){
    return mOptions.value
  },
  addOption(option: any) {
    mOptions.value =[
      ...mOptions.value,
      option
    ]
  }
}
defineExpose(regisiter)
</script>
<style lang="less" scoped>

</style>